/**
 * 1.接口加密
 */
// 参数无filename
var now = Date.now();
// 获取 Body 参数对象
var queryParams = pm.request.url.body;
// 修改 body 参数（如不存在则新增）
queryParams.upsert({
  key: 'timestamp',
  value: now.toString(),
});
console.log('新增标签时间');
//获取全局参数
var sm2_key = pm.environment.get('sm2_key');

fox.liveRequire(['sm-crypto', 'js-base64', 'gm-crypt'], ([sm, base, sm4]) => {
  //生成一个16位随机数，作为SM4的秘钥
  const randomlyGenerateA16bitString = () => {
    const name = '123';
    const $chars = sm.sm3(Date.parse(new Date()) + name); // 杂凑
    const maxPos = $chars.length;
    let str = '';
    for (let i = 0; i < 16; i++) {
      str += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return str;
  };

  const SM2_Encrypt = async (key) => {
    const cipher_ciphertext = sm.sm2.doEncrypt(key, sm2_key, 1);
    return cipher_ciphertext; // 加密结果
  };
  const SM3_Encrypt = (loginParams) => {
    const new_params = loginParams;
    //TODO:排序按字母从小到大排序 递归遍历每一个对象的属性
    loginParams = sortKeysRecursive(new_params);
    const hashcode = sm.sm3(JSON.stringify(loginParams));
    return hashcode;
  };

  const SM4_Encrypt = (hashcode, key) => {
    try {
      const SM4 = sm4;
      const sm4Config = {
        key: key,
        mode: 'ecb',
        cipherType: 'base64',
      };
      const sm4_1 = new SM4(sm4Config);
      const decodeData = sm4_1.encrypt(hashcode);
      return decodeData;
    } catch (e) {
      console.log('error->>>>>>>>->', e);
    }
  };

  //递归排序
  function sortKeysRecursive(obj) {
    if (typeof obj !== 'object' || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(sortKeysRecursive);
    }
    const sortedObj = {};
    Object.keys(obj)
      .sort()
      .forEach((key) => {
        sortedObj[key] = sortKeysRecursive(obj[key]);
      });

    return sortedObj;
  }

  try {
    //参数合并
    const sm3_params = {};

    //业务参数
    const encry_params = {};
    //1.随机函数
    const key = randomlyGenerateA16bitString();
    const B = SM2_Encrypt(key);
    const hashcode = SM3_Encrypt(sm3_params);
    const A = SM4_Encrypt(hashcode, key);
    //业务参数加密
    const paramstr = SM4_Encrypt(JSON.stringify(encry_params), key);
    const result = {
      sign: { H: A, S: B },
      sm4key: key,
      paramstr: paramstr,
    };
    queryParams.upsert({
      key: 'sign',
      value: result.sign,
    });
    queryParams.upsert({
      key: 'params',
      value: result.paramstr,
    });
  } catch (error) {
    console.log('签名失败', error);
  }
});
